package com.zcs.app.lucky.helper

import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.sxw.android.base.utils.JLogUtil
import com.zcs.autolayout.utils.AutoUtils

/**
 * 吸顶工具
 */
class CeilingBuilder {
    private lateinit var recyclerView: RecyclerView
    private lateinit var ceilingTv: TextView
    private var listener: ((position: Int) -> Unit)? = null
    private var childId: Int = 0

    fun recyclerView(rv: RecyclerView): CeilingBuilder {
        this.recyclerView = rv
        return this
    }

    fun ceilingTv(tv: TextView): CeilingBuilder {
        this.ceilingTv = tv
        return this
    }

    fun childId(id: Int): CeilingBuilder {
        this.childId = id
        return this
    }

    fun listener(listener: (position: Int) -> Unit): CeilingBuilder {
        this.listener = listener
        return this
    }

    fun build() {
        /**
         * Check if this view can be scrolled vertically in a certain direction.
         *
         * @param direction Negative to check scrolling up, positive to check scrolling down.
         * @return true if this view can be scrolled in the specified direction, false otherwise.
         * 返回false表示不能往下滑动，即代表到顶部了
         */
        val canScrollVertically = recyclerView.canScrollVertically(-1)
        ceilingTv.visibility = if (canScrollVertically) View.VISIBLE else View.GONE

        // 获取第一个可见元素的position值 - findFirstVisibleItemPosition
        val layoutManager = recyclerView.layoutManager as GridLayoutManager
        val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()
        JLogUtil.d("onScrolled called with firstVisibleItemPosition = $firstVisibleItemPosition")
        if (firstVisibleItemPosition < 0) {
            return
        }
        // 返回 第一个可见元素的position值
        listener?.let { it(firstVisibleItemPosition) }

        var height = ceilingTv.height
        if (height <= 0) height = AutoUtils.getPercentWidthSize(139)
        // findChildViewUnder
        val stickyView = recyclerView.findChildViewUnder(100f, height.toFloat())
        if (stickyView != null) {
            val tag = stickyView.findViewById<View>(childId)
            if (tag != null) {
                val top = stickyView.top
                if (top > 0) {
                    val dealtY = top - ceilingTv.measuredHeight
                    ceilingTv.translationY = dealtY.toFloat()
                } else {
                    ceilingTv.translationY = 0f
                }
            } else {
                ceilingTv.translationY = 0f
            }
        }
    }
}